<template>
  <div class="container" v-loading.fullscreen.lock="fullscreenLoading">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>运行管理</el-breadcrumb-item>
      <el-breadcrumb-item>工作质量反馈</el-breadcrumb-item>
      <el-breadcrumb-item>排班管理</el-breadcrumb-item>
      <el-breadcrumb-item>{{ programme }}</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="tableColumns">
      <h5>新增排班</h5>
      <el-form ref="mainForm" :rules="rules" label-width="120px" :inline="false" :model="ruleForm.mainForm"
               class="demo-form-inline">
        <div class="content">
          <el-row>
            <el-col :span="12">
              <el-form-item label="排班方案" prop="schemeName">
                <el-input v-model="ruleForm.mainForm.schemeName" :disabled="typeId!='0'&&typeId!='4'" maxlength="30"
                          style="margin-bottom: 10px"/>
                <span v-if="schemeNameDate == ruleForm.mainForm.schemeName && typeId == '4'"
                      style="color: #f56c6c;position: absolute;top: 30px">
                  请更换排班方案！
                </span>

              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="排班类型" prop="classType">
                <el-radio-group v-model="ruleForm.mainForm.classType" :disabled="typeId!='0'" @input="changeClassType">
                  <el-radio
                    v-for="(item, index) in classTypeOptions.slice(1, classTypeOptions.length)"
                    :key="index"
                    :label="item.value">
                    {{ item.label }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="排班班次" prop="schemeClasses">
                <div class="tagChose">
                  <el-tag v-for="tag in ruleForm.mainForm.schemeClasses" :key="tag.id"
                          style="margin-right: 10px;color:#606266"
                          :closable="tag.id!='0'" :color="tag.color" @close="handleClose(tag)" :hit="false">
                    {{ tag.className }}
                  </el-tag>
                </div>
                <el-button type="primary" @click="selectClass" v-if="typeId=='0'||typeId=='4'">选择</el-button>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="排班模式" prop="schemeModel">
                <el-select v-model="ruleForm.mainForm.schemeModel" :disabled="typeId!='0'" placeholder="请选择"
                           style="width: 100%"
                           @change="modelChange">
                  <el-option
                    v-for="item in schemeModelOptions.slice(1, schemeModelOptions.length)"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="排班周期" prop="schemeDate">
                <el-select v-model="ruleForm.mainForm.schemeDate" :disabled="typeId==='0'||typeId==='1'||typeId=='2'"
                           placeholder="请选择"
                           style="width: 100%"
                           @change="schemeDateChange">
                  <el-option
                    v-for="item in ruleForm.schemeDateOptions"
                    :key="item.value"
                    :label="item.value"
                    :value="item.value">
                  </el-option>
                </el-select>
                <span v-if="schemeCopyDate == ruleForm.mainForm.schemeDate && typeId == '4'"
                      style="color: #f56c6c;position: absolute;top: 30px">
                  请更换排班周期！
                </span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="打卡要求：" label-width="120px" style="display: flex; align-items: center"
                            prop="clockRequire">
                <el-checkbox v-model="ruleForm.mainForm.chekIn" :disabled="typeId!='0'&&typeId!='4'" label="上班打卡"
                             size="large"/>
                <el-checkbox v-model="ruleForm.mainForm.chekOut" :disabled="typeId!='0'&&typeId!='4'" label="下班打卡"
                             size="large"/>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <h5 style="margin-bottom: 20px">实时排班</h5>
      <el-table
        :data="ruleForm.schemeDetailTable"
        :min-height="'35rem'"
        style="width: 100%;border:1px solid #ebeef5;"
        border
        class="elTable"
        header-row-class-name="headerClass"
      >
        <el-table-column
          v-for="(item, index) in scheduleDetailTableColumns(ruleForm.mainForm.schemeDate,'details')"
          :key="index"
          :min-width="item.minWidth"
          :fixed="item.fixed"
          :align="item.align"
          show-overflow-tooltip
        >
          <template #header>
            <div v-if="item.prop === 'name'&&typeId!=='2'">
              {{ ruleForm.mainForm.schemeModel == 1 ? item.label : '班组' }}
              <el-icon @click="setPerson" class="tableHeaderIco">
                <Plus/>
              </el-icon>
            </div>
            <div v-else-if="item.prop.indexOf('formatDate') > -1" class="header">
                <span v-if="ruleForm.holiday.get(item.day)"
                      class="holidayText"
                      :class="ruleForm.holiday.get(item.day)?.status === 0 ? 'holiday': 'work'">
                  {{ ruleForm.holiday.get(item.day)?.status === 0 ? '休' : '班' }}</span>
              <span v-else class="holidayText"></span>
              <span class="day" :style="{color: item.color ? item.color : '#909399'}">{{ item.label }}</span>
            </div>
            <span v-else>{{ item.label }}</span>
          </template>
          <template #default="scope">
            <span v-if="item.prop === 'name'">
              {{ scope.row[item.prop] }}
              <el-icon class="tableDefaultIco" @click="removePerson(scope.row)"><Delete/></el-icon>
            </span>
            <span v-else-if="item.prop.indexOf('formatDate') < 0">{{ scope.row[item.prop] }}</span>
            <div v-else>
              <!--班次选择pop框-->
              <el-popover
                :visible="ruleForm.editSchedual.item?.prop === item?.prop && ruleForm.editSchedual.row === scope.row"
                placement="bottom"
                trigger="click"
                :title="null"
                :width="'18rem'">
                <el-row>
                  <el-col :span="24">
                    <el-tabs v-model="ruleForm.tabActive" @tab-click="handleClick">
                      <el-tab-pane label="更换班次" name="1" v-if="typeId!='2'">
                        <el-select v-model="ruleForm.editSchedual.classId" placeholder="请选择"
                                   style="margin-bottom: 10px">
                          <el-option
                            v-for="item in ruleForm.classDetailTableOptions"
                            :key="item.id"
                            :label="item.showText"
                            :value="item.id">
                          </el-option>
                        </el-select>
                      </el-tab-pane>
                      <el-tab-pane label="人员代班" name="2"
                                   v-if="isSubstitute">
                        <el-select v-model="ruleForm.editSchedual.substituteId" placeholder="请选择"
                                   v-if="ruleForm.mainForm.schemeModel==1" :disabled="typeId=='2'">
                          <el-option
                            v-for="item in substituteArr"
                            :key="item.staffId"
                            :label="item.name"
                            :value="item.staffId"
                            :disabled="item.disabled">
                          </el-option>
                        </el-select>
                        <div style="position: absolute;font-size: 24px;top:0px;right:0;cursor: pointer"
                             v-if="ruleForm.mainForm.schemeModel!=1&&typeId !== '2'&&substituteArr.length>1"
                             @click="addMore(item, scope.row,index)">+
                        </div>
                        <div v-for="(mores,moresInx) in ruleForm.editSchedual.dbscheduleReqList"
                             style="display: flex;justify-content:flex-start;margin-top: 24px"
                             v-if="ruleForm.mainForm.schemeModel!=1">
                          <div
                            style="width:7.5rem;text-align: center;display: flex;flex-direction: column;margin-bottom: 10px">
                            <label>被代班人</label>
                            <el-select v-model="mores.schedulerId" placeholder="请选择">
                              <el-option
                                v-for="item in teamsArr"
                                :key="item.staffId"
                                :label="item.name"
                                :value="item.staffId"
                                :disabled="item.disabled">
                              </el-option>
                            </el-select>
                          </div>
                          <div
                            style="width:7.5rem;text-align: center;display: flex;flex-direction: column;margin-left: 10px">
                            <label>代班人</label>
                            <el-select v-model="mores.substituteId" placeholder="请选择">
                              <el-option
                                v-for="item in substituteArr"
                                :key="item.staffId"
                                :label="item.name"
                                :value="item.staffId"
                                :disabled="item.disabled">
                              </el-option>
                            </el-select>
                          </div>
                          <div style="position: relative;font-size: 24px;top:18px;right:0;cursor: pointer"
                               v-if="ruleForm.mainForm.schemeModel!=1&&typeId !== '2'&&substituteArr.length>1&&moresInx>0"
                               @click="delMore(item, scope.row,moresInx)">-
                          </div>
                        </div>
                      </el-tab-pane>
                    </el-tabs>
                  </el-col>
                </el-row>
                <div style="text-align: center; margin-top: 23px">
                  <el-button @click="cancelSchedual()">关闭</el-button>
                  <el-button type="primary" @click="saveSchedual(item, scope.row)" v-if="typeId !== '2'">确定
                  </el-button>
                </div>
                <template #reference>
                  <div class="schedualClass"
                       :style="{ backgroundColor: scope.row.dailyDetailMap.get(item.prop)?.color }"
                       @click="setSchedual(item, scope.row)">
                    {{ scope.row.dailyDetailMap.get(item.prop)?.className }}
                    <span v-if="ruleForm.mainForm.schemeModel==1&&scope.row.dailyDetailMap.get(item.prop)?.substituteId"
                          class="substituteText">代</span>
                    <span v-else-if="ruleForm.mainForm.schemeModel!=1&&scope.row.dailyDetailMap.get(item.prop)?.dbscheduleReqList&&scope.row.dailyDetailMap.get(item.prop)?.dbscheduleReqList.length>0
                    &&scope.row.dailyDetailMap.get(item.prop)?.dbscheduleReqList[0].substituteId"
                          class="substituteText">代</span>
                    <el-icon class="substituteHoliday"
                             v-if="ruleForm.holiday.get(item.day)&&scope.row.dailyDetailMap.get(item.prop)!=undefined"
                             @click.stop="openElMessageBox()">
                      <WarningFilled/>
                    </el-icon>
                  </div>
                </template>
              </el-popover>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div style="display: flex;position: absolute;bottom: 0;left:40%">
        <el-button @click="$router.go(-1)">取消</el-button>
        <el-button type="primary" v-if="typeId !== '2'" v-loading="showSubmit" @click="submitForm(mainForm)">保存
        </el-button>
      </div>
    </div>

    <!--班次选择-->
    <el-dialog
      v-model="ruleForm.classDialogVisible"
      title="选择班次"
      width="30%"
      draggable
      align-center
      @closed="closedDialog"
    >
      <el-form>
        <el-form-item label="班次类型" prop="classType">
          <el-select v-model="ruleForm.mainForm.classType" disabled>
            <el-option
              v-for="item in classTypeOptions.slice(1, classTypeOptions.length)"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-table
          ref="multipleTableRef"
          v-if="ruleForm.mainForm.classType==='S'"
          :data="ruleForm.classDetailTable"
          style="width: 100%"
          @selection-change="handleSelect"
          :row-class-name="rowClassName"
        >
          <el-table-column type="selection" width="55"/>
          <el-table-column property="className" label="班次名称" min-width="100" ellipsis align="center">
            <template #default="scope">{{ scope.row.className }}</template>
          </el-table-column>
          <el-table-column property="stime" label="开始时间" min-width="100" align="center"/>
          <el-table-column property="etime" label="结束时间" wmin-width="100" align="center"/>
        </el-table>
        <el-table
          v-else
          ref="multipleTableRef"
          :data="ruleForm.classDetailTable"
          style="width: 100%"
          @selection-change="handleSelect"
          :row-class-name="rowClassName">
          <el-table-column type="selection" width="55"/>
          <el-table-column property="className" label="班次名称" min-width="100" ellipsis align="center">
            <template #default="scope">{{ scope.row.className }}</template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
            <span class="dialog-footer">
              <el-button @click="closedDialog">取消</el-button>
              <el-button type="primary" @click="saveClass">确定</el-button>
            </span>
      </template>
    </el-dialog>
    <!--人员选择-->
    <el-dialog
      v-model.sync="ruleForm.personData.show"
      :title="ruleForm.personData.title"
      width="650px"
      draggable
      align-center
      v-loading="ruleForm.loading"
      @closed="cancelPerson"
    >
      <!--选择班组-->
      <template v-if="ruleForm.mainForm.schemeModel==1">
        <el-transfer v-model="selectNodes" :data="ruleForm.personData.personList" filterable
                     :props="{key: 'staffId',label: 'name',}"
                     :filter-method="filterMethod" :titles="['待选区', '已选区']"
        />
      </template>
      <template v-else>
        <CustomTransfer
          :filter-method="filterPerson"
          v-model="ruleForm.personData.selectPersons"
          :value="ruleForm.personData.selectPersons"
          :isShow="ruleForm.personData.show"
          :types="ruleForm.mainForm.schemeModel"
          :classType="ruleForm.mainForm.classType"
          :data="ruleForm.personData.personList"
          @change="changeValue"/>
      </template>
      <template #footer>
              <span class="dialog-footer">
                <el-button @click="ruleForm.personData.show = false">取消</el-button>
                <el-button type="primary" :loading="showPersonLoading" @click="savePerson">确定</el-button>
              </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, watch } from 'vue'
import moment from 'moment'
import { classTypeOptions, schemeModelOptions } from './config/options'
import { scheduleDetailTableColumns } from './config/columns'
import type { FormInstance, ElTable } from 'element-plus'

import { ElMessage, ElMessageBox } from 'element-plus'
import { rules } from './config/rules'
import { useRoute } from 'vue-router'
import {
  groupList,
  staffList,
  findSchedule,
  isSchedule,
  getEmpNot,
  findEmployee,
  detailScheduleSchemeV1,
  updateScheduleSchemeV1, getHoliday, scheduleSchemeDel, addScheduleSchemeV1
} from '@/api/quality/schedule'
import CustomTransfer from './components/customTransfer.vue'

interface Option {
  key: number
  label: string
}

const mainForm = ref<FormInstance>()
const multipleTableRef = ref<InstanceType<typeof ElTable>>()
//面包屑动态字段
const programme = ref<string>('')
//获取路由
const router = useRoute()
//从路由里获取参数
const typeId = ref('0')
const detailsType = router.query.type
const nodeRowData = router.query.nodeRowData
const tableId = router.query.tableId
//如果是当天是某个月最后一天就默认选择下一个月
let lastData = moment(new Date()).startOf('day').add(1, 'days').format('YYYY-MM')
let nowData = moment().format('YYYY-MM')
let schemeDate = lastData != nowData ? lastData : nowData
// 编辑页面的数据
const ruleForm = reactive({
  loading: false,
  editId: null,
  mainForm: {
    schemeName: null,
    classType: '',
    schemeClasses: ref<any>([]),
    schemeModel: null,
    schemeDate: schemeDate,
    chekIn: null,
    chekOut: null,
  },
  schemeDateOptions: [{ // 排班周期选项
    value: schemeDate
  }, {
    value: moment(schemeDate).add(1, 'months').format('YYYY-MM')
  }, {
    value: moment(schemeDate).add(2, 'months').format('YYYY-MM')
  }],

  ruleOptions: ref<any>([]), // 排班规则
  classDialogVisible: false, // 班次选择显隐
  classDetailTable: ref<any>([]), // 详细班次数据
  classDetailTableOptions: ref<any>([]), // 可选的班次
  classDetailTableMap: new Map(), // 可选的班次map
  editSchedual: { // 编辑中的排班
    classId: null,
    item: null,
    row: null,
    substituteId: null,
    dbscheduleReqList: [{}],
  },
  status: -1,//排班状态
  schemeDetailTable: ref<any>([]), // 排班详情
  personData: {
    show: false,
    title: '选择人员',
    personList: ref<Option[]>(),
    personMap: new Map(),
    selectPersons: []
  },
  holiday: new Map(),
  tabActive: '1'
})
const show = ref<boolean>(false)
const title = ref<String>('')

const changeValue = (value: any) => {
  ruleForm.personData.selectPersons = value
}
const fullscreenLoading = ref(false)
const schemeCopyDate = ref('')
const schemeNameDate = ref('')
const detailPerson = ref([])
const ruleFormSchemeDetailTable = ref([])

// 添加代班人员租
const addMore = (item, row, index) => {
  row.dailyDetailMap?.get(item.prop)?.dbscheduleReqList.push({})
}
const delMore = (item, row, moresInx) => {
  ruleForm.editSchedual.dbscheduleReqList.splice(moresInx, 1)
}
// 设置默认数据
const intDetail = async () => {
  const resp = await detailScheduleSchemeV1(tableId)
  if (resp.code === '1') {
    let {
      schemeName,
      classType,
      schemeModel,
      schemeDate,
      chekIn,
      chekOut,
      schemeClasses,
      qualityScheduleQUsers,
    } = resp.data
    //复制的时候  排班周期必须改日期
    schemeCopyDate.value = schemeDate
    schemeNameDate.value = schemeName
    typeId.value = resp.data.status + ''
    if (router.query.type == '2') {
      typeId.value = '2'
    } else if (router.query.type == '4') {
      typeId.value = '4'
    }
    console.log('======typeId=', typeId.value)
    //调用班次接口
    const respClass = await findSchedule({ classType: classType })
    if (respClass?.code == '1') {
      ruleForm.classDetailTable = []
      respClass.data.forEach((item: any) => {
        let classDetail = JSON.parse(eval('(' + item.classDetail + ')'))
        item.stime = classDetail.date[0]
        item.etime = classDetail.date[1]
      })
      respClass.data.push({
        className: '休息',
        color: '#cdcdcd',
        id: '0'
      })
      ruleForm.classDetailTable = respClass.data
    }
    //表单数据赋值
    ruleForm.mainForm = {
      schemeName,
      classType,
      schemeModel,
      schemeDate,
      chekIn: chekIn === 1 ? true : false,
      chekOut: chekOut === 1 ? true : false,
    }
    let schemeArrs = schemeClasses.split(',')
    let schemeObjArrs = []
    respClass.data.forEach((itemDetail) => {
      schemeArrs.forEach((schemeItem) => {
        if (schemeItem == itemDetail.id) {
          schemeObjArrs.push(itemDetail)
        }
      })
    })
    ruleForm.mainForm.schemeClasses = schemeObjArrs
    loadSelectClass()
    //  表格数据赋值
    let respStaff: any = null
    let respGroup: any = null
    //根据不同的排班模式调用不同的接口
    if (schemeModel === 1) {
      respStaff = await staffList({ createDept: nodeRowData })
      console.log(respStaff.data)
      console.log('----', qualityScheduleQUsers)
      if (respStaff?.code == '1') {
        respStaff.data.forEach((itemStaff: any) => {
          qualityScheduleQUsers.forEach((userItem) => {
            if (userItem.teamId == itemStaff.staffId) {
              itemStaff.isDisabled = true
            } else {
              //itemStaff.isDisabled = false
            }
          })
          itemStaff.label = itemStaff.name
          itemStaff.id = itemStaff.staffId
          itemStaff.children = itemStaff.children || []
        })
        ruleForm.personData.personList = respStaff.data || []
      }
    } else {
      respGroup = await groupList(nodeRowData)
      if (respGroup?.code == '1') {
        ruleForm.personData.personList = deepFn(respGroup.data) || []
      }
    }
    let qualityScheduleArr: { name: any; id: any; teamId: any; countWork: any; countPlan: any; dailyDetailMap: Map<any, any>; dailyDetail: never[]; }[] = []
    qualityScheduleQUsers.forEach((itemRow: any) => {
      let personDataPersonList: any = []
      if (schemeModel === 1) {
        personDataPersonList = respStaff.data
      } else {
        personDataPersonList = filterTreeArray(JSON.parse(JSON.stringify(deepFn(respGroup.data))))
      }
      let dailyDetailMaps = new Map()
      itemRow.qualityScheduleDetailList.forEach((personResp) => {
        dailyDetailMaps.set('formatDate' + personResp.scheduleDate, {
          scheduleDate: personResp.scheduleDate,
          classId: personResp.classId,
          className: personResp.classesName,
          color: personResp.color,
          substituteId: personResp.substituteId,
          dbscheduleReqList: personResp.dbscheduleReqList == null || personResp.dbscheduleReqList.length == 0 ? [{}] : personResp.dbscheduleReqList,
          classTime: [personResp.officeHours, personResp.closingTime],
          teamId: personResp.teamId,
          workDay: 1
        })
      })
      let personArr: any = null
      personDataPersonList.forEach((personItem) => {
        if (personItem.id == itemRow.teamId) {
          personArr = personItem
          ruleForm.personData.selectPersons.push(personItem)
        }
      })
      if(personArr!=null){
        let node = {
          name: personArr?.name,
          id: personArr?personArr:'',
          teamId: itemRow.teamId,
          countWork: itemRow.countWork,
          countPlan: itemRow.countPlan,
          dailyDetailMap: dailyDetailMaps,
          dailyDetail: []
        }
        qualityScheduleArr.push(node)
      }

    })
    ruleForm.schemeDetailTable = qualityScheduleArr
    ruleFormSchemeDetailTable.value = qualityScheduleArr
  }
}
//展开树状图
const filterTreeArray = (array: any) => {
  let newData: any[] = []
  const callback = (item: any) => {
    (item.children || (item.children = [])).map((v: any) => {
      callback(v)
    })
    delete item.children
    newData.push(item)
  }
  array.map((v: any) => callback(v))
  return newData
}
const showSubmit = ref(false)
const isExistScheduling = ref(false)
// 保存按钮触发事件
const submitForm = (formEl: FormInstance | undefined) => {

  mainForm.value.validate((valid) => {
    if (valid) {
      //判断是否添加排班人或班组
      if (ruleForm.schemeDetailTable.length == 0) {
        ElMessage.error('请添加排班！')
        return
      }
      //判断是否排班
      let isShowScheme = false
      ruleForm.schemeDetailTable.forEach((item: any) => {
        if (item.dailyDetailMap.size == 0) {
          isShowScheme = true
        }
      })
      if (isShowScheme) {
        ElMessage.error('请添加排班内容！')
        return
      }
      //数据组装
      let {
        schemeDate,
        classType,
        schemeModel,
        schemeName,
        schemeClasses,
        chekIn,
        chekOut
      } = ruleForm.mainForm
      //组装排班班次id数组
      let arrs: any[] = []
      schemeClasses.forEach((item) => {
        arrs.push(item.id)
      })
      //组装排班详情数据
      let qualityScheduleQUsers: { teamId: any; qualityScheduleDetailList: any[]; }[] = []
      ruleForm.schemeDetailTable.forEach((item: any) => {
        let qualityScheduleDetailList: any[] = []
        item.dailyDetailMap.forEach((value, key) => {
          qualityScheduleDetailList.push({
            ...value,
            classesName: value.className,
            schemeDate,
            classesType: classType,
            officeHours: value.classTime[0],
            closingTime: value.classTime[1],
            createDept: nodeRowData,
            scheduleDate: value.scheduleDate,
            substituteId: value.substituteId,
            dbscheduleReqList: schemeModel == 2 ? value.dbscheduleReqList == undefined ? [] : value.dbscheduleReqList : [],
            name: item.name,
          })
        })
        let node = {
          teamId: item.id.id,
          countPlan: item.countPlan,
          countWork: item.countWork,
          qualityScheduleDetailList: qualityScheduleDetailList
        }
        qualityScheduleQUsers.push(node)
      })
      let parem = {
        chekIn: chekIn ? 1 : 0,
        chekOut: chekOut ? 1 : 0,
        classType,
        deptId: nodeRowData,
        qualityScheduleQUsers: qualityScheduleQUsers,
        schemeClasses: arrs.join(','),
        schemeDate,
        schemeModel,
        schemeName,
        schemeRule: null,
      }
      showSubmit.value = true
      if (typeId.value == '4') {
        if (schemeNameDate.value == schemeName) {
          ElMessage.warning('请更换排班方案！')
          showSubmit.value = false
          return
        }
        if (schemeCopyDate.value == schemeDate) {
          ElMessage.warning('请更换排班周期！')
          showSubmit.value = false
          return
        }
        if (isExistScheduling.value) {
          ElMessage.warning('当前周期,已存在排班！')
          showSubmit.value = false
          return
        }
        addScheduleSchemeV1(parem).then(resp => {
          if (resp.code === '1') {
            showSubmit.value = false
            ElMessage.success('新增成功！')
            window.history.go(-1)
          } else {
            showSubmit.value = false
            ElMessage.error(res?.message || '操作失败，请重试！')
          }
        }).catch(err => {
          showSubmit.value = false
        })
      } else {
        parem.id = tableId
        updateScheduleSchemeV1(parem).then(resp => {
          if (resp.code === '1') {
            showSubmit.value = false
            ElMessage.success('编辑成功！')
            window.history.go(-1)
          } else {
            showSubmit.value = false
            ElMessage.error(res?.message || '操作失败，请重试！')
          }
        }).catch(err => {
          showSubmit.value = false
        })
      }
    } else {
      return
    }
  })
}

const handleClose = (tag: string) => {
  ruleForm.mainForm.schemeClasses.splice(ruleForm.mainForm.schemeClasses.indexOf(tag), 1)
  delSchemeDetailTable()
}
// 给表格设置选中
// const classTableMounted = () => {
//   selectClass()
// }
const selectArr = ref([])
const handleSelect = (selection: any) => {
  selectArr.value = selection
}
const handleSelectAll = (selection: any) => {
  selectArr.value = selection
}
const changeClassType = () => {
  this.$confirm('是否要切换切换会清空信息', '确认切换?', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    this.value = name
    this.value1 = this.options2[name]
  })
  ruleForm.mainForm.schemeClasses = []
  ruleForm.schemeDetailTable = ref<any>([])
  ruleForm.personData.selectPersons = []
  getFindSchedule()
}
// 加载可选的排班
const loadSelectClass = () => {
  ruleForm.classDetailTableOptions = []
  ruleForm.classDetailTableMap.clear()
  ruleForm.mainForm.schemeClasses?.forEach((resp: any) => {
    resp.showText = resp.className
    if (resp.classType === 'S') {
      resp.showText += '(' + resp.stime + '~' + resp.etime + ')'
    }
    // if(resp.id!='0'){
    //   ruleForm.classDetailTableOptions.push(resp)
    //   ruleForm.classDetailTableMap.set(resp.id, resp)
    // }
    ruleForm.classDetailTableOptions.push(resp)
    ruleForm.classDetailTableMap.set(resp.id, resp)
  })
}
// 选择班次
const selectClass = () => {
  ruleForm.classDialogVisible = true
  setTimeout(() => {
    ruleForm.mainForm.schemeClasses?.forEach((c: any) => {
      multipleTableRef.value!.toggleRowSelection(c, true)
    })
  }, 500)
}
// 确定班次选择
const saveClass = () => {
  selectArr.value.push({
    className: '休息',
    color: '#cdcdcd',
    id: '0',
    showText: '休息'
  })
  ruleForm.mainForm.schemeClasses = newArrFn(selectArr.value)
  delSchemeDetailTable()
  ruleForm.classDialogVisible = false
  loadSelectClass()
}
const delSchemeDetailTable = () => {
  //删除班次后,需要将表格已排的删除
  ruleForm.schemeDetailTable.forEach((saveItem: any) => {
    console.log(saveItem,'dasdasdas')
    let dailyDetailMap=new Map()
    saveItem.dailyDetailMap.forEach((dailyItme: any, Keys: any) => {
      let  delKeysName=''
      ruleForm.mainForm.schemeClasses.forEach((itemClasses: any) => {
        if (itemClasses.id == dailyItme.classId) {
          dailyDetailMap.set(Keys, dailyItme)
        }
      })
    })
    saveItem.dailyDetailMap=dailyDetailMap
  })
}
const newArrFn = (arr) => {
  const res = new Map()
  return arr.filter(arr => !res.has(arr.id) && res.set(arr.id, arr.id))
}
// 关闭班次选择框
const closedDialog = () => {
  ruleForm.classDialogVisible = false
  multipleTableRef.value!.clearSelection()
}
//递归添加标识
const deepFn = (data = []) => {
  data.forEach((item: any) => {
    if (item.children !== null && item.children.length > 0) {
      item.isDisabled = true
      item.label = item.name
      item.children = item.children || []
      deepFn(item.children)
    } else {
      item.isDisabled = false
      item.label = item.name
      item.children = item.children || []
    }
  })
  return data
}
// 选择人员/班组
const selectNodes = ref([])
const setPerson = () => {

  if (ruleForm.mainForm.schemeModel == 1) {
    selectNodes.value = []
    ruleForm.schemeDetailTable.forEach((item) => {
       selectNodes.value.push(item.id.staffId)
    })
  }else{
    ruleForm.personData.selectPersons=[]
    ruleForm.schemeDetailTable.forEach((item) => {
      ruleForm.personData.selectPersons.push(item.id)
    })
  }
  ruleForm.personData.show = true
}
// 关闭人员/班组选择
const cancelPerson = () => {
  ruleForm.personData.show = false
}
const showPersonLoading = ref(false)
// 保存人员/班组选择
const savePerson = () => {
  let personsIdArr: any[] = []
  if (ruleForm.mainForm.schemeModel == 1) {
    //人

    ruleForm.personData.personList.forEach((p) => {
      if (p.isDisabled) {
        selectNodes.value = selectNodes.value.filter(r => {
          return r != p.id
        })
      }
    })
    personsIdArr = selectNodes.value
  } else {
    //班组
    ruleForm.personData.selectPersons.forEach((p: Option) => {
      personsIdArr.push(p.id)
    })
  }
  showPersonLoading.value = true
  isSchedule(ruleForm.mainForm.schemeModel, ruleForm.mainForm.schemeDate, personsIdArr.join(',')).then(resp => {
    if (resp.code === '1') {
      if (resp.data.length === 0) {
        ruleForm.schemeDetailTable = []
        if (ruleForm.mainForm.schemeModel == 1) {
          //按人
          ruleForm.personData.personList.forEach(p => {
            selectNodes.value.forEach(item => {
              if (p.id == item) {
                ruleForm.schemeDetailTable.push({
                  id: p,
                  name: p.label,
                  countWork: 0,
                  countPlan: 0,
                  dailyDetailMap: new Map(),
                  dailyDetail: []
                })
                ruleForm.schemeDetailTable.forEach((item) => {
                  if (item.id.staffId == p.staffId) {
                    if (p.dailyDetailMap !== undefined) {
                      item.dailyDetailMap = p.dailyDetailMap
                      p.dailyDetailMap.forEach((seeValue) => {
                        if (seeValue.classTime != undefined) {
                          let dayTime = ruleForm.mainForm.schemeDate + '-' + seeValue.scheduleDate
                          let hores = timediff(dayTime + ' ' + seeValue.classTime[0], dayTime + ' ' + seeValue.classTime[1])
                          item.countPlan += hores
                          item.countPlan = Number(item.countPlan.toFixed(1))
                        } else {
                          item.countPlan = 0
                        }
                      })
                    } else {
                      item.dailyDetailMap = new Map()
                    }
                  }
                })

              }
            })
          })
        } else {
          //按班组
          ruleForm.personData.selectPersons.forEach(p => {
            ruleForm.schemeDetailTable.push({
              id: p,
              name: p.label,
              countWork: 0,
              countPlan: 0,
              dailyDetailMap: new Map(),
              dailyDetail: []
            })
            ruleForm.schemeDetailTable.forEach((item) => {
              if (item.id.staffId == p.staffId) {
                if (p.dailyDetailMap !== undefined) {
                  item.dailyDetailMap = p.dailyDetailMap
                  p.dailyDetailMap.forEach((seeValue) => {
                    if (seeValue.classTime != undefined) {
                      let dayTime = ruleForm.mainForm.schemeDate + '-' + seeValue.scheduleDate
                      let hores = timediff(dayTime + ' ' + seeValue.classTime[0], dayTime + ' ' + seeValue.classTime[1])
                      item.countPlan += hores
                      item.countPlan = Number(item.countPlan.toFixed(1))
                    } else {
                      item.countPlan = 0
                    }
                  })
                } else {
                  item.dailyDetailMap = new Map()
                }
              }
            })

          })
        }
        ruleForm.schemeDetailTable.unshift(...ruleFormSchemeDetailTable.value)
        cancelPerson()
      } else {
        let messageArr = []
        resp.data.forEach((item) => {
          let personDataPersonList = []
          if (ruleForm.mainForm.schemeModel === 1) {
            personDataPersonList = ruleForm.personData.personList
          } else {
            personDataPersonList = filterTreeArray(JSON.parse(JSON.stringify(ruleForm.personData.personList)))
          }
          personDataPersonList.forEach((respRow) => {
            if (item.schedulerORteamId == respRow.id) {
              messageArr.push(respRow.name)
            }
          })
        })
        ElMessage.error(messageArr.join(',') + '在' + ruleForm.mainForm.schemeDate + '月，已存在排班')
        cancelPerson()
      }
      showPersonLoading.value = false
    }
  })

}
// 人员过滤
const filterPerson = (query: string, item: Option) => {
  return item.label.toLowerCase().includes(query.toLowerCase())
}
// 移除排班人员
const removePerson = (row: any) => {
  ruleForm.personData.selectPersons.splice(ruleForm.personData.selectPersons.indexOf(row.id, 1))
  ruleForm.schemeDetailTable.splice(ruleForm.schemeDetailTable.indexOf(row), 1)
  ruleForm.personData.personList.forEach(item => {
    if (row.teamId == item.staffId) {
      item.isDisabled = false
    }
  })
}
const isSubstitute = ref(false)
// 排班详情选择班次
const setSchedual = (item: any, row: any) => {
  if (typeId.value != '2' || row.dailyDetailMap?.get(item.prop).substituteId != null || row.dailyDetailMap?.get(item.prop).dbscheduleReqList[0].substituteId != undefined) {
    if (compareDate(item)) {
      isSubstitute.value = false
      if (row.dailyDetailMap?.get(item.prop) != undefined) {
        if (row.dailyDetailMap?.get(item.prop)?.classId == '0') {
          isSubstitute.value = false
        } else {
          isSubstitute.value = true
        }
      }
      ruleForm.editSchedual.item = item
      ruleForm.editSchedual.row = row
      ruleForm.editSchedual.classId = row.dailyDetailMap?.get(item.prop)?.classId

      ruleForm.editSchedual.substituteId = row.dailyDetailMap?.get(item.prop)?.substituteId
      ruleForm.editSchedual.dbscheduleReqList = row.dailyDetailMap?.get(item.prop)?.dbscheduleReqList
      if (typeId.value == '2') {
        ruleForm.tabActive = '2'
      } else {
        ruleForm.tabActive = '1'
      }
      if (row.dailyDetailMap?.get(item.prop) == undefined) {
        ruleForm.classDetailTableOptions = ruleForm.classDetailTableOptions.filter((itemsFilter: any) => itemsFilter.id != 0)
      } else {
        loadSelectClass()
      }
      const p= ruleForm.classDetailTableOptions.filter(item=>item.id==ruleForm.editSchedual.classId)
      if(p.length==0){
        ruleForm.editSchedual.classId = row.dailyDetailMap?.get(item.prop)?.className
      }
      handleClick(ruleForm.tabActive)
    }
  }
}
const compareDate = (item) => {
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  const timestamp = today.getTime()
  const compareDate = new Date(ruleForm.mainForm.schemeDate + '-' + item.day)
  compareDate.setHours(0, 0, 0, 0)

  if (timestamp - compareDate.getTime() >= 0) {
    return false
  } else {
    return true
  }
}
//tab切换
const handleClick = (tab: any) => {
  if (tab == '1') {
    teamsClass()
  } else {
    substituteClass()
  }
}
// 取消排班详情班次选择
const cancelSchedual = () => {
  ruleForm.editSchedual.item = null
  ruleForm.editSchedual.classId = null
  ruleForm.editSchedual.row = null
}
const isConfirm = ref(false)
// 保存排班详情班次选择
const saveSchedual = (item: any, row: any) => {
  const thisClass = ruleForm.classDetailTableMap.get(ruleForm.editSchedual.classId)
  if (thisClass.id !== '0' && ruleForm.tabActive == '1') {
    if (ruleForm.mainForm.classType === 'S') {
      schedulingData(item, row)
    } else if (ruleForm.mainForm.classType === 'F') {
      fixedClass(item, row)
    } else {
      shiftSystem(item, row)
    }
  } else {
    let substituteDataArrs = []
    if (ruleForm.editSchedual.dbscheduleReqList != undefined) {
      ruleForm.editSchedual.dbscheduleReqList.forEach((otherResp) => {
        let node = {
          schedulerId: otherResp.schedulerId,
          substituteId: otherResp.substituteId,
          scheduleDate: item.day,
        }
        substituteDataArrs.push(node)
      })
    }
    let substituteId = ''
    if (ruleForm.editSchedual.substituteId != undefined || ruleForm.editSchedual.dbscheduleReqList != undefined) {
      substituteId = ruleForm.editSchedual.substituteId || substituteDataArrs[0].schedulerId
    }
    row.dailyDetailMap.set('formatDate' + item.day, {
      scheduleDate: item.day,
      classId: ruleForm.editSchedual.classId,
      className: ruleForm.classDetailTableMap.get(ruleForm.editSchedual.classId)?.className,
      color: ruleForm.classDetailTableMap.get(ruleForm.editSchedual.classId)?.color,
      substituteId: substituteId,
      dbscheduleReqList: substituteDataArrs,
      classTime: ['00:00', '00:00'],
      workDay: 1
    })
  }
  row.countPlan = 0
  ruleForm.schemeDetailTable.forEach((seeSchemeDeta) => {
    seeSchemeDeta.dailyDetailMap.forEach((seeValue) => {
      if (seeSchemeDeta.id.id === row.id.id) {
        if (seeValue.classTime != undefined) {
          let dayTime = ruleForm.mainForm.schemeDate + '-' + item.day
          let hores = timediff(dayTime + ' ' + seeValue.classTime[0], dayTime + ' ' + seeValue.classTime[1])
          row.countPlan += hores
          row.countPlan = Number(row.countPlan.toFixed(1))
        }
      }
    })
  })
  ruleForm.personData.selectPersons.forEach((item) => {
    if (item.staffId == row.id.staffId) {
      item.dailyDetailMap = row.dailyDetailMap
    }
  })
  isConfirm.value = true
  cancelSchedual()
}
// 排版制
const schedulingData = (item: any, row: any) => {
  const thisClass = ruleForm.classDetailTableMap.get(ruleForm.editSchedual.classId)
  let classDetail = JSON.parse(eval('(' + thisClass.classDetail + ')'))
  row.dailyDetailMap.set('formatDate' + item.day, {
    scheduleDate: item.day,
    classId: ruleForm.editSchedual.classId,
    className: ruleForm.classDetailTableMap.get(ruleForm.editSchedual.classId)?.className,
    color: ruleForm.classDetailTableMap.get(ruleForm.editSchedual.classId)?.color,
    substituteId: ruleForm.editSchedual.substituteId,
    dbscheduleReqList: ruleForm.editSchedual.dbscheduleReqList,
    classTime: classDetail.date,
    workDay: 1
  })
}
// 固定班制度
const fixedClass = (item: any, row: any) => {
  let initDailyDetailMap = row.dailyDetailMap
  const thisClass = ruleForm.classDetailTableMap.get(ruleForm.editSchedual.classId)
  let classDetail = JSON.parse(eval('(' + thisClass.classDetail + ')'))
  let classDetailDate = []
  classDetail.date.forEach((itemDates: any) => {
    if (itemDates.dateStr != '' && itemDates.dateStr != null && itemDates.dateStr != undefined) {
      classDetailDate.push(itemDates)
    }
  })
  row.dailyDetailMap = new Map()
  let columnsData = scheduleDetailTableColumns(ruleForm.mainForm.schemeDate, 'details')
  let spliceColumnsData = columnsData.splice(3, columnsData.length)
  spliceColumnsData.forEach((itemColumns: any) => {
    if (classDetailDate.length !== 0) {
      classDetailDate.forEach((classDate) => {
        if (itemColumns.weekDayTxt === classDate.dayText) {
          if (classDate.dateStr != '') {
            if (itemColumns.day >= item.day) {
              row.dailyDetailMap.set('formatDate' + itemColumns.day, {
                scheduleDate: itemColumns.day,
                classId: ruleForm.editSchedual.classId,
                className: ruleForm.classDetailTableMap.get(ruleForm.editSchedual.classId)?.className,
                color: ruleForm.classDetailTableMap.get(ruleForm.editSchedual.classId)?.color,
                substituteId: ruleForm.editSchedual.substituteId,
                dbscheduleReqList: ruleForm.editSchedual.dbscheduleReqList,
                classTime: classDate.dateStr,
                workDay: 1
              })
            } else {
              initDailyDetailMap.forEach((itemsInit: any) => {
                if (itemsInit.scheduleDate < item.day) {
                  row.dailyDetailMap.set('formatDate' + itemsInit.scheduleDate, {
                    ...itemsInit
                  })
                }
              })
            }
          } else {
            row.dailyDetailMap.set('formatDate' + itemColumns.day, {
              scheduleDate: itemColumns.day,
              className: '休息',
              color: '#cdcdcd',
              id: '0'
            })
          }
        }
      })
    }
  })
}
//轮班制度
const shiftSystem = (item: any, row: any) => {
  let initDailyDetailMap = row.dailyDetailMap
  const thisClass = ruleForm.classDetailTableMap.get(ruleForm.editSchedual.classId)
  let classDetail = JSON.parse(eval('(' + thisClass.classDetail + ')'))
  row.dailyDetailMap = new Map()
  let columnsData = scheduleDetailTableColumns(ruleForm.mainForm.schemeDate, 'details')
  let spliceColumnsData = columnsData.splice(3, columnsData.length)
  let loopNum = 1
  spliceColumnsData.forEach((itemColumns: any, index: number) => {
    if (itemColumns.day >= item.day) {
      if (parseInt(classDetail.date.workDay) >= loopNum) {
        row.dailyDetailMap.set('formatDate' + itemColumns.day, {
          scheduleDate: itemColumns.day,
          classId: ruleForm.editSchedual.classId,
          className: ruleForm.classDetailTableMap.get(ruleForm.editSchedual.classId)?.className,
          color: ruleForm.classDetailTableMap.get(ruleForm.editSchedual.classId)?.color,
          substituteId: ruleForm.editSchedual.substituteId,
          dbscheduleReqList: ruleForm.editSchedual.dbscheduleReqList,
          classTime: classDetail.date.dateList[loopNum - 1].date,
          workDay: 1
        })
      } else {
        let loopAllDay = parseInt(classDetail.date.workDay) + parseInt(classDetail.date.restDay)
        if (loopNum >= loopAllDay) {
          loopNum = 0
        }
      }
      loopNum++
    } else {
      initDailyDetailMap.forEach((itemsInit: any) => {
        if (itemsInit.scheduleDate < item.day) {
          row.dailyDetailMap.set('formatDate' + itemsInit.scheduleDate, {
            ...itemsInit
          })
        }
      })
    }
  })
}
//计算时间差
const timediff = (beginTime, endTime) => {
  //年月日时分秒转换为时间戳
  let beginTimes = (new Date(beginTime).getTime()) / 1000
  let endTimes = (new Date(endTime).getTime()) / 1000
  var starttime = ''
  var endtime = ''
  if (beginTimes < endTimes) {
    starttime = beginTimes
    endtime = endTimes
  } else {
    starttime = endTimes
    endtime = beginTimes
  }
  //计算天数
  var timediff = endtime - starttime
  //计算小时数
  var remain = timediff % 86400
  var hours = Number((remain / 3600).toFixed(1))

  return hours
}
// 冲突验证，row:detailMap里需要验证的一条，id：排班对象的ID
const clash = (row: any, id: string) => {
  const param = {
    schemeId: null,
    classId: ruleForm.editSchedual.classId,
    schemeDate: ruleForm.mainForm.schemeDate,
    scheduleDate: row.scheduleDate,
    schemeObj: id,
  }
  if (ruleForm.editId) {
    param.schemeId = ruleForm.editId
  }
  // clashJuge(param).then((res: { code: string; data: any }) => {
  //   if (res.code === '1') {
  //     if (res.data) {
  //       row.clash = true
  //     } else {
  //       row.clash = false
  //     }
  //   }
  // })
}
const substituteArr = ref([])
const teamsArr = ref([])

// 获取代班人是否有班次
const substituteClass = () => {
  let lastDay = ruleForm.editSchedual.item.day < 10 ? '0' + ruleForm.editSchedual.item.day : ruleForm.editSchedual.item.day
  let day = ruleForm.mainForm.schemeDate + '-' + lastDay
  getEmpNot(day, nodeRowData).then(resp => {
    if (resp.code == '1') {
      let moreSubstitute: any[] = []
      //获取表格所有的天数据
      ruleForm.schemeDetailTable.forEach((items) => {
        items.dailyDetailMap.forEach((itemsMap) => {
          if (itemsMap.scheduleDate == ruleForm.editSchedual.item.day) {
            if (ruleForm.mainForm.schemeModel == 1) {
              moreSubstitute.push(itemsMap.substituteId)
            } else {
              itemsMap.dbscheduleReqList.forEach((resps) => {
                moreSubstitute.push(resps.substituteId)
              })
            }
          }

        })
      })
      console.log(moreSubstitute)
      resp.data.forEach((moresItme) => {
        moreSubstitute.forEach((itemsAll) => {
          if (moresItme.staffId == itemsAll) {
            moresItme.disabled = true
          }
        })
      })
      substituteArr.value = resp.data
    }
  })
}
//获取被代班人
const teamsClass = () => {
  findEmployee({
    groupId: ruleForm.editSchedual.row.teamId,
  }).then(resp => {
    if (resp.code == '1') {
      teamsArr.value = resp.data
    }
  })
}
// 排班模式变更
const modelChange = () => {
  ruleForm.personData.selectPersons = []
  ruleForm.schemeDetailTable = []
  ruleFormSchemeDetailTable.value = []
  if (ruleForm.mainForm.schemeModel === 1) {
    ruleForm.personData.title = '选择人员'
    getStaffList()
  } else {
    ruleForm.personData.title = '选择班组'
    getGroupList()
  }
}
// 排班周期变更
const schemeDateChange = () => {
  if (ruleForm.mainForm.classType == 'F' && typeId.value == '4') {
    let personsIdArr: any[] = []
    let columnsData = scheduleDetailTableColumns(ruleForm.mainForm.schemeDate, 'details')
    let spliceColumnsData = columnsData.splice(3, columnsData.length)
    ruleFormSchemeDetailTable.value.forEach((tableItem: any) => {
      personsIdArr.push(tableItem.teamId)
      //获取选择的班次
      let classId = tableItem.dailyDetailMap.entries().next().value[1].classId
      let classObj = {}
      ruleForm.mainForm.schemeClasses.forEach((item: any) => {
        if (classId == item.id) {
          classObj = item
        }
      })
      //拼装复制更改排班周期
      let dailyDetailMap = new Map()
      let classDetail = JSON.parse(eval('(' + classObj.classDetail + ')'))
      let classDetailDate = []
      classDetail.date.forEach((itemDates: any) => {
        if (itemDates.dateStr != '' && itemDates.dateStr != null && itemDates.dateStr != undefined) {
          classDetailDate.push(itemDates)
        }
      })
      spliceColumnsData.forEach((itemColumns: any) => {
        if (classDetailDate.length !== 0) {
          classDetailDate.forEach((classDate) => {
            if (itemColumns.weekDayTxt === classDate.dayText) {
              if (classDate.dateStr != '') {
                dailyDetailMap.set('formatDate' + itemColumns.day, {
                  scheduleDate: itemColumns.day,
                  classId: classObj.id,
                  className: classObj.className,
                  color: classObj.color,
                  substituteId: '',
                  dbscheduleReqList: [],
                  classTime: classDate.dateStr,
                  workDay: 1
                })
              }
            }
          })
        }
      })
      tableItem.dailyDetailMap = dailyDetailMap
    })
    isSchedule(ruleForm.mainForm.schemeModel, ruleForm.mainForm.schemeDate, personsIdArr.join(',')).then(resp => {
      if (resp.code == '1') {
        if (resp.data.length !== 0) {
          let messageArr = []
          resp.data.forEach((item) => {
            let personDataPersonList = []
            if (ruleForm.mainForm.schemeModel === 1) {
              personDataPersonList = ruleForm.personData.personList
            } else {
              personDataPersonList = filterTreeArray(JSON.parse(JSON.stringify(ruleForm.personData.personList)))
            }
            personDataPersonList.forEach((respRow) => {
              if (item.schedulerORteamId == respRow.id) {
                messageArr.push(respRow.name)
              }
            })
          })
          isExistScheduling.value = true
          ElMessage.error(messageArr.join(',') + '在' + ruleForm.mainForm.schemeDate + '月，已存在排班')
        } else {
          isExistScheduling.value = false
        }
      }
    })
    ruleForm.schemeDetailTable = ruleFormSchemeDetailTable
  } else {
    ruleForm.schemeDetailTable = ruleFormSchemeDetailTable
  }
  loadHoliday()
}

//查询班次
const getFindSchedule = async () => {
  const params = {
    classType: ruleForm.mainForm.classType
  }
  const resp = await findSchedule(params)
  if (resp?.code == '1') {
    ruleForm.classDetailTable = []
    resp.data.forEach((item: any) => {
      let classDetail = JSON.parse(eval('(' + item.classDetail + ')'))
      item.stime = classDetail.date[0]
      item.etime = classDetail.date[1]
    })
    resp.data.push({
      className: '休息',
      color: '#cdcdcd',
      id: '0'
    })
    ruleForm.classDetailTable = resp.data
  }
}
//获取人员
const getStaffList = async () => {
  const params = {
    createDept: nodeRowData
  }
  const resp = await staffList(params)
  if (resp?.code == '1') {
    resp.data.forEach((item: any) => {
      item.isDisabled = false
      item.label = item.name
      item.id = item.staffId
      item.children = item.children || []
    })
    ruleForm.personData.personList = resp.data || []
  }
}
//获取班组
const getGroupList = async () => {
  const resp = await groupList(nodeRowData)
  if (resp?.code == '1') {
    ruleForm.personData.personList = deepFn(resp.data) || []
  }
}
onMounted(() => {
  switch (typeId) {
    case '2':
      programme.value = '查看排班方案'
      break
    case '3':
      programme.value = '编辑排班方案'
      break
  }
  intDetail()
})
watch(() => [ruleForm.mainForm.schemeClasses], (newValue, oldValue) => {
  console.log(newValue, oldValue)
})
watch(() => [ruleForm.mainForm.schemeDate], (newValue, oldValue) => {
  if (newValue[0] != oldValue[0]) {
    loadHoliday()
  }
})
const filterMethod = (query, item) => {
  return item.name.toLowerCase().includes(query.toLowerCase())
}
// 加载节假日
const loadHoliday = async () => {
  const resp = await getHoliday(ruleForm.mainForm.schemeDate)
  if (resp?.code == '1') {
    ruleForm.holiday.clear()
    console.log(resp.data, '查看数据')
    resp.data.forEach((l: any) => {
      ruleForm.holiday.set(l.day, l)
    })
  }
}
const openElMessageBox = () => {
  ElMessageBox.alert('所选排班日期为节假日，请关注!', '警告', {
    confirmButtonText: '关闭',
    customStyle: { width: '20%' },
    center: true,
    callback: () => {
    },
  })
}
const rowClassName = ({ row }) => {
  if (row.id == '0') {
    return 'showRow'
  }
}
onMounted(() => {
  loadHoliday()
})

</script>

<style lang="less" scoped>

//@import "../style/publicStyle.less";
/deep/ .elTable .cell {
  white-space: pre-line !important;
  text-align: center;
  padding: 0;
  margin: 0;
  width: 100% !important;
}

/deep/ .elTable .el-table__cell {
  padding: 0;
  margin: 0;
}

.header {
  display: flex;
  justify-content: space-between;
  flex-direction: column;

  .holidayText {
    width: 1rem;
    height: 1rem;
    line-height: 1rem;
    font-size: 12px;
    font-weight: normal;
    color: white;
    border-radius: 0.2rem;

    &.holiday {
      background-color: #9fd546;
    }

    &.work {
      background-color: #f0514c;
    }
  }
}

/deep/ .el-input__suffix {
  display: none;
}

.el-breadcrumb {
  padding: 12px 24px;
  line-height: 22px;
}

/deep/ .el-breadcrumb__inner {
  color: #989DAA;
}

.container {
  .tableColumns {
    height: 810px;
    flex-direction: column;
    background-color: #FFFFFF;
    margin: 0 15px;
    padding: 12px 24px;
    border-radius: 5px;
    position: relative;

    .addProgramme {
      height: 280px;
    }

    .realTimeProgramme {
      height: 550px;
    }

    .title-span {
      margin-top: 15px;
    }


    .content {
      width: 90%;
      margin: 10px auto;

      .tagChose {
        border-radius: 5px;
        height: 33px;
        box-shadow: 0 0 0 1px #dcdfe6 inset;
        padding: 0 10px;
        width: 80%;
        margin-right: 20px
      }
    }

    .schedualClass {
      //display: inline-block;
      position: relative;
      width: 100%;
      padding: 0 5%;
      height: 4rem;
      line-height: 4rem;
      color: #000;
      cursor: pointer;
      //border-radius: 0.5rem;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }

    .substituteText {
      display: inline-block;
      position: absolute;
      top: 0.3rem;
      left: 0.3rem;
      width: 1rem;
      height: 1rem;
      line-height: 1rem;
      background-color: #81d3f8;
      border-radius: 0.2rem;
      font-size: 0.7rem;
    }

    .substituteHoliday {
      color: #D9001B;
      position: absolute;
      top: 0;
      right: 0;
      width: 2rem;
      height: 2rem;
      line-height: 1rem;
      z-index: 999999;
    }

    .clashText {
      display: inline-block;
      position: absolute;
      top: 0;
      right: 0;
      width: 2rem;
      height: 1rem;
      line-height: 1rem;
      background-color: #d9001b;
      border-radius: 0.2rem;
      font-size: 0.7rem;
    }
  }

  .schedulingCalendar {
    height: 400px;
    margin: 0 35px;
  }

  .btnBox {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 35px;
  }
}


.tableHeaderIco {
  cursor: pointer;
  background: #307FEF;
  color: #fff;
  padding: 2px;
  border-radius: 5px;
  font-weight: bold;
  font-size: 14px;
  position: absolute;
  top: 10px;
  right: 10px;
}

.tableDefaultIco {
  cursor: pointer;
  background: #F6444C;
  color: #fff;
  padding: 2px;
  border-radius: 5px;
  font-weight: bold;
  font-size: 14px;
  position: absolute;
  top: 10px;
  right: 10px;
}

/deep/ .headerClass {
  background: #F3F5F9 !important;

  th.el-table__cell {
    background: #F3F5F9 !important;
  }
}

::v-deep .showRow {
  display: none;
}

</style>
